/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.setup.trac.controller;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.dialect.Dialect;
import org.hibernate.transform.ResultTransformer;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.setup.trac.pojo.Tickets;
import com.setup.trac.pojo.condition.FindTicketByStatoOrProject;
import com.setup.trac.pojo.condition.TicketsFinderByProgettiUtenteAndStatoApertoInCarico;
import com.setup.trac.pojo.transformer.TicketsResultTransformer;
import com.setup.trac.pojo.wrappers.TicketView;
import com.setup.trac.pojo.wrappers.UtentiView;
import com.setup.trac.service.SearchService;
import com.setup.trac.util.Browser;
import com.setup.trac.util.SQLCondition;
import com.setup.trac.util.TracSetupUtil;

/**
 * 
 * @author edoardo
 */
public class SearchController extends AbstractController {

	private SearchService searchService;
	private TracSetupUtil tracSetupUtil;
	private Map<String, Browser> browsers;
	private Dialect dialect;
	private Logger log = Logger.getLogger("tracsetup");
	private Properties sqlProperties;

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String show = request.getParameter("showDesc");
		UtentiView loginForm = (UtentiView) request.getSession().getAttribute(
				"loginForm");
		Browser browser = browsers.get(loginForm.getUtenti().getProfilo()
				.getDescrizione());
		TicketView[] tickets = new TicketView[0];
		Object cc = null;
		boolean filtra = request.getParameter("filtraTicket") != null;
		String sql = null;
		String where = "";
		if (filtra) {
			String byProject = request.getParameter("searchByProject");
			String byStato = request.getParameter("searchByStato");
			String byOwners = request.getParameter("searchByOwner");
			String byCliente = request.getParameter("searchByCliente");
			sql = getSqlProperties().getProperty("sql.tickets.count2");
			filtra = false;
			if (byProject != null && !"-1".equals(byProject)) {
				where += "id_progetto=" + byProject + " and ";
				filtra = true;
			}
			if (byStato != null && !"-1".equals(byStato)) {
				where += "stato_ticket=" + byStato + " and ";
				filtra = true;
			}else{
				if(loginForm.getUtenti().getProfilo().getDescrizione().equals("ADMINISTRATOR")){
					where+="stato_ticket in (1,2,3,4) and ";
				}
			}
			if (byOwners != null && !"-1".equals(byOwners)) {
				where += "id_owner=" + byOwners + " and ";
				filtra = true;
			}
			if (byCliente != null && !"-1".equals(byCliente)) {
				where += "id_utente=" + byCliente + " and ";
				filtra = true;
			}
			if (filtra) {
				where = where.substring(0,
						where.toLowerCase().lastIndexOf("and"));
				where = " where " + where;
			}

			sql = MessageFormat.format(sql, where);
			log.debug(sql);
			BigDecimal[] countTickets = getSearchService().find(
					new BigDecimal[0], sql, null);
			cc = countTickets[0];

		} else {
			if (loginForm.getUtenti().getProfilo().getDescrizione()
					.equals("DEVELOPER")
					|| loginForm.getUtenti().getProfilo().getDescrizione()
							.equals("ADMINISTRATOR")) {
				sql = getSqlProperties().getProperty("sql.tickets.count");
				if (loginForm.getUtenti().getProfilo().getDescrizione()
						.equals("ADMINISTRATOR")) {
					sql = MessageFormat.format(sql, loginForm.getUtenti()
							.getIdUtente().toPlainString(), where, ",3,4");
				} else {
					sql = MessageFormat.format(sql, loginForm.getUtenti()
							.getIdUtente().toPlainString(), where,"");
				}
				BigDecimal[] countTickets = getSearchService().find(
						new BigDecimal[0], sql, null);
				log.debug(sql);
				cc = countTickets[0];
			}
			if (loginForm.getUtenti().getProfilo().getDescrizione()
					.equals("USER")) {
				cc = new TicketsFinderByProgettiUtenteAndStatoApertoInCarico(
						loginForm.getUtenti());
			}
		}

		Page thePage = browser.impaginaRicerca(request, cc, Tickets.class);

		if (cc instanceof SQLCondition) {
			tickets = searchService.findTickets((SQLCondition) cc,
					thePage.getFirstRecord());
		}
		if (cc instanceof BigDecimal) {
			if (request.getParameter("filtraTicket") == null) {
				// eseguo la query filtrando per utente loggato e ticket
				// "aperti" e "in carico"
				sql = sqlProperties.getProperty("sql.tickets.developer");

				if (loginForm.getUtenti().getProfilo().getDescrizione()
						.equals("ADMINISTRATOR")) {
					sql = MessageFormat.format(sql, loginForm.getUtenti()
							.getIdUtente().toPlainString(), where, ",3,4");
				} else {
					sql = MessageFormat.format(sql, loginForm.getUtenti()
							.getIdUtente(), where,"");
				}
				log.debug(sql);
			} else {
				sql = sqlProperties.getProperty("sql.tickets.developer2");

				sql = MessageFormat.format(sql, where);
			}
			Class _class = getDialect().getClass();
			Method mLimitString = _class.getDeclaredMethod("getLimitString",
					String.class, boolean.class);
			mLimitString.setAccessible(true);
			sql = (String) mLimitString.invoke(getDialect(), sql, true);
			log.debug(sql);
			ResultTransformer transformer = new TicketsResultTransformer();
			Tickets[] ts = getSearchService().find(
					new Tickets[0],
					sql,
					transformer,
					thePage.getFirstRecord()
							+ getSearchService().getMaxResults(),
					thePage.getFirstRecord());
			tickets = new TicketView[ts.length];
			for (int i = 0; i < ts.length; i++) {
				Tickets t = ts[i];
				tickets[i] = new TicketView();
				tickets[i].setTickets(t);
			}

			;
		}

		// }
		// else{
		if (show != null && "true".equalsIgnoreCase(show)) {
			// SQLCondition sqlCondition = new TicketFinderByIdTicket(request
			// .getParameter("id"));
			// Tickets ticket = getSearchService().find(new Tickets[0],
			// sqlCondition, Tickets.class)[0];
			// request.setAttribute("showDescrizione", new Boolean(true));
			// Set<StoricoTicket> setStorico = ticket.getStoricoTickets();
			// StoricoTicket[] st = setStorico.toArray(new StoricoTicket[0]);
			// Arrays.sort(st, new
			// StoricoTicketOrderByDataModifica(OrderBy.DESC));
			//
			// request.setAttribute("storico", st);
		}
		request.getSession().setAttribute("risultatoRicercaTicket", tickets);

		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("risultatoRicerca");
		return modelAndView;
	}

	public Dialect getDialect() {
		return this.dialect;
	}

	public SearchService getSearchService() {
		return searchService;
	}

	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}

	public TracSetupUtil getTracSetupUtil() {
		return tracSetupUtil;
	}

	public void setTracSetupUtil(TracSetupUtil tracSetupUtil) {
		this.tracSetupUtil = tracSetupUtil;
	}

	public Map<String, Browser> getBrowsers() {
		return browsers;
	}

	public void setBrowsers(Map<String, Browser> browsers) {
		this.browsers = browsers;
	}

	public void setDialect(Dialect dialect) {
		this.dialect = dialect;
	}

	public Properties getSqlProperties() {
		return sqlProperties;
	}

	public void setSqlProperties(Properties sqlProperties) {
		this.sqlProperties = sqlProperties;
	}

}
